package com.gitee.taotaojs.mybootsuper.utils;

import com.alibaba.fastjson.JSON;
import com.gitee.taotaojs.mybootsuper.vo.HttpResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author TaoTaojs
 * @date 2020/9/1 5:05 PM
 * <p>Description</p>
 * <h2>功能描述</h2>
 * HTTP工具类
 * <h3>主要功能：</h3>
 * <ol>
 *     <li>获取reqeust对象</li>
 *     <li>输出信息到浏览器</li>
 * </ol>
 * <h3>关联类</h3>
 * <p>参考链接：</p>
 * <h2>更新日志</h2>
 * [author]        [time]                      [version]          [desc]
 * TaoTaojs        2020/9/1 5:05 PM             V1.0              获取reuqest对象与输出信息到浏览器
 */

public final class HttpUtils {

    private HttpUtils(){}

    /**
     * 获取HttpServletRequest对象
     * @return HttpServletRequest对象
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 输出信息到浏览器
     * @param response response
     * @param data 数据
     * @throws IOException 输出输出异常
     */
    public static void write(HttpServletResponse response, Object data) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        HttpResult result = HttpResult.ok(data);
        String json = JSON.toJSONString(result);
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();
    }

}
